<?php
/**
 * This file is part of HelloWorld
 *
 */
namespace api\modules\outapi\controllers;

use api\models\ChargeOrderModel;
use common\models\ElectricCardPayFlowModel;
use common\models\MemberCouponModel;
use Yii;

class ChargeOrderController extends BaseController
{
    /**
     * 根据手机号查询用户.
     * @return array
     */
    public function actionDetail()
    {
        $orderNo = Yii::$app->request->post('order_no');
        if (! $orderNo) {
            $orderNo = Yii::$app->request->get('order_no');
        }
        if (! $orderNo) {
            return $this->toJson(-1, '订单不存在', [], true);
        }
        $order = ChargeOrderModel::findOne(['order_no' => $orderNo]);

        if (! $order) {
            return $this->toJson(-1, '订单不存在', [], true);
        }

        return $this->toJson(0, '成功', $order->toArray(), true);
    }

    /**
     * 根据手机号查询用户.
     * @return array
     */
    public function actionList()
    {
        $params = Yii::$app->request->get() + ['limit' => 20, 'page' => 1];
        $model = new ChargeOrderModel();
        $result = $model->advanceSearch($params, '*', false);

        return $this->toJson($result);
    }

    public function actionFlowList()
    {
        $limit = Yii::$app->request->post('limit', 20);
        $page = Yii::$app->request->post('page', 1);
        $start_date = Yii::$app->request->post('start_date');
        $end_date = Yii::$app->request->post('end_date');
        $select = Yii::$app->request->post('select', 'order.pay_amount,flow.order_no,flow.pay_way,flow.pay_time');
        $model = ElectricCardPayFlowModel::find()->from(['flow' => ElectricCardPayFlowModel::tableName()]);
        $model->innerJoin(['order' => ChargeOrderModel::tableName()], 'flow.order_no = order.order_no');
        $model->select($select);
        $model->where(['flow.pay_status' => 1, 'flow.pay_type' => 2])->andWhere(['>', 'flow.total_fee', 0]);
        $model->andFilterWhere(['>=', 'flow.pay_time', $start_date]);
        $model->andFilterWhere(['<=', 'flow.pay_time', $end_date]);
        $model->limit($limit)->offset(($page - 1) * $limit)->orderBy('flow.id DESC');
        $result = $model->asArray()->all();

        return $this->toJson(0, '查询成功', $result);
    }

    public function actionCouponBusinessLine()
    {
        $order_no = Yii::$app->request->post('order_no');
        $result    = ElectricCardPayFlowModel::find()
            ->select('mc.business_line')
            ->from(['flow' => ElectricCardPayFlowModel::tableName()])
            ->innerJoin(['mc' => MemberCouponModel::tableName()], 'flow.member_coupon_id = mc.id')
            ->where(['>', 'flow.member_coupon_id', 0])
            ->andWhere(['flow.order_no' => $order_no, 'flow.pay_status' => 1, 'flow.pay_type' => 2])
            ->asArray()
            ->one();
        return $this->toJson(0, '查询成功', $result);
    }
}
